using System.Collections.Generic;
using NodeCanvas.Framework;
using UnityEngine;
using Yoozoo.Gameplay.Liberty;
using Yoozoo.Gameplay.Liberty.AI.Node;

namespace com.yoozoo.gta
{
    public class NpcIsNearGrenade : AIConditionBaseNode
    {
        public float ReactLikelihood = 1;
        public BBParameter<List<GameObject>> m_Grenades;

        protected override string OnInit()
        {
            base.OnInit();
            if (_entity.npcTrigger != null)
            {
                _entity.npcTrigger.onTriggerEnterAction += OnTriggerEnterAction;
                _entity.npcTrigger.onTriggerExitAction += OnTriggerExitAction;
            }
            return null;
        }
        
        protected override bool OnCheck()
        {
            if (Random.value > ReactLikelihood) 
            {
                return false;
            }

            // Remove the grenade reference as soon as it explodes.
            for (int i = m_Grenades.value.Count - 1; i > -1; --i) {
                if (!m_Grenades.value[i].activeSelf) {
                    m_Grenades.value.RemoveAt(i);
                }
            }
            // The agent should react if there are any grenades within the list.
            return (m_Grenades.value.Count > 0);
        }

        // protected override void OnStop()
        // {
        //     base.OnStop();
        //     if (_entity.npcTrigger != null)
        //     {
        //         _entity.npcTrigger.onTriggerEnterAction -= OnTriggerEnterAction;
        //         _entity.npcTrigger.onTriggerExitAction -= OnTriggerExitAction;
        //     }
        // }
        private void OnTriggerEnterAction(Collider other)
        {
            // Only be afraid of a grenade thrown by somebody else.
            var grenade = other.gameObject.GetComponent<Grenade>();
            if (grenade != null) {
                if (grenade.Owner != _entity && !m_Grenades.value.Contains(other.gameObject)) {
                    m_Grenades.value.Add(other.gameObject);
                }
            }
        } 
        private void OnTriggerExitAction(Collider other)
        {
            // Only be afraid of a grenade thrown by somebody else.
            var grenade = other.gameObject.GetComponent<Grenade>();
            if (grenade != null) {
                if (grenade.Owner != _entity && m_Grenades.value.Contains(other.gameObject)) {
                    m_Grenades.value.Remove(other.gameObject);
                }
            }
        }
    }
}
